package com.baiduspring.function.elasticsearch.connect;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 通过单例模式获取客户端对象
 * <p>
 * ＠author 熊彦
 * ＠date 2017-12-04
 */
@Slf4j
public final class ClientSingle {
    private ClientSingle() {
    }

    public static TransportClient openConnection() {
        return $T.get();
    }

    private final static class $T {
        private static TransportClient client;

        static {
            try {
                client = new PreBuiltTransportClient(Settings.EMPTY)
                        .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
            } catch (UnknownHostException e) {
                log.error("ES client创建错误：", e);
            }
        }

        private static TransportClient get() {
            return client;
        }
    }
}